package com.quectel.business.contentaudit;

import com.quectel.util.common.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/5/15 14:52
 * @description new java file header...
 */
@Component
public class ValidatorChain {
    private final List<Validator<ValidatorContext>> validators;

    @Autowired
    public ValidatorChain(List<Validator<ValidatorContext>> validators) {
        this.validators = sort(validators);
    }

    private List<Validator<ValidatorContext>> sort(List<Validator<ValidatorContext>> validators) {
        return validators.stream()
                .sorted(Comparator.comparingInt(Validator::getPriority))
                .collect(Collectors.toList());
    }

    public Response validate(ValidatorContext article) {
        for (Validator<ValidatorContext> validator : validators) {
            Response validate = validator.validate(article);
            if (!validate.isSuccess()) {
                return validate;
            }
        }
        return Response.ok();
    }

    public Response invalidateCache(ValidatorContext article) {
        validators.forEach(validator -> validator.invalidCache(article));
        return Response.ok();
    }

}
